package com.google.code.head2head.gwtmodules.server;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.code.head2head.model.Entry;

public class FileUploadServlet extends HttpServlet {

	

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			
			//todo: recuperer l'utilisateur enregistré dans cette session
			//si pas d'utilisateur créer une nouvelle entry à partir de son adresse ip
			
			String entryUploadedFileDirectory = getServletContext().getRealPath(".")+"/images/dummyEntry";
			
			//creates the new entry
			Entry entry=new Entry();
			entry.setFistImageUrl(entryUploadedFileDirectory+"/image1.jpg");
			entry.setFistImageUrl(entryUploadedFileDirectory+"/image2.jpg");
			
			//save the entry
			
			
			// Create a factory for disk-based file items
			FileItemFactory factory = new DiskFileItemFactory();

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Parse the request
			List items = upload.parseRequest(request);

			// Process the uploaded items
			Iterator iter = items.iterator();
			int i=1;
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
					File uploadedFile = new File(entryUploadedFileDirectory
							+ "/image"+i+".jpg");
					item.write(uploadedFile);
					i+=1;
			}

			response.getWriter().write("File uploaded");

		} catch (Exception e) {
			response.getWriter().write(
					"Problem during file upload : " + e.getMessage());
		}
	}

}
